#include "widget.h"
#include <QHBoxLayout>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QString>
#include "ccurvedata.h"
#include <QDebug>
widget::widget(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle("2D Example");

    m_chartView = new ChartViewEx;
//    QHBoxLayout *mainLayout = new QHBoxLayout;
//    mainLayout->addWidget(m_chartView);
//    setLayout(m_chartView);
    m_chartView->setChartName("Test");
    m_chartView->setXAxisName("X");
    m_chartView->setYAxisName("Y");
    this->setCentralWidget(m_chartView);
    addAction = new QAction(QIcon(":/Image/Image/add.png"),tr("Add"),this);
    addAction->setStatusTip("Add a group data");
    connect(addAction,SIGNAL(triggered(bool)),this,SLOT(AddData()));

    deleteAction = new QAction(QIcon(":/Image/Image/delete.png"),tr("Delete"),this);
    deleteAction->setStatusTip("Delete all data");
    connect(deleteAction,SIGNAL(triggered(bool)),this,SLOT(DeleteAllData()));

   dataToolBar = addToolBar("Data");
   dataToolBar->addAction(addAction);
   dataToolBar->addAction(deleteAction);
}

widget::~widget()
{

}

void widget::AddData()
{
  QString fileName = QFileDialog ::getOpenFileName(this,"Select one files to open","/home", "CSV (*.csv)");

  if(!fileName.isEmpty())
  {
      QFile file(fileName);

      CCurveData data;
      QList<float> lstX;
      QList<float> lstY;
      if(file.open(QIODevice::ReadOnly | QIODevice::Text))
      {
          QTextStream textStream(&file);
          while (!textStream.atEnd()) {
              QString str = textStream.readLine();
              QStringList lst;
              lst = str.split(',');

              bool okX,okY;
              float x = lst.at(0).toFloat(&okX);
              float y = lst.at(1).toFloat(&okY);
              if(okX && okY)
              {
//                  qDebug()<<x<<","<<y;
                 lstX.append(x);
                 lstY.append(y);
              }
          }
      }
      else
      {
          QMessageBox::warning(this,"Prompt:","The file has not opened!");
          return;
      }

      data.SetData(lstX,lstY);
      m_chartView->AddCurveData(&data);
  }
}

void widget::DeleteAllData()
{
    m_chartView->ClearAll();
}
